import { Inject, Provide, Scope, ScopeEnum } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/orm';
import { CoolEvent, Event } from '@cool-midway/core';
import { ImUserEntity } from '../entity/user';
import { Repository } from 'typeorm';
import { ImSocketEvent } from '../socket/event';
import { ImUserService } from '../service/user';
import { UserInfoService } from '../../user/service/info';
/**
 * 接收事件
 */
@Provide()
@Scope(ScopeEnum.Singleton)
@CoolEvent()
export class ImEvent {
  @InjectEntityModel(ImUserEntity)
  imUserEntity: Repository<ImUserEntity>;

  @Inject()
  imSocketEvent: ImSocketEvent; 

  @Inject()
  imUserService: ImUserService;

  @Inject()
  userInfoSrv: UserInfoService;
  
 
 
  @Event('updateUser')
  async updateUser(param, type) {
    await this.imUserEntity.update(
      { id: param.id },
      { headimg: param.headimg, nickname: param.nickname }
    );
  }
  @Event('updateAdmin')
  async updateAdmin(param) {
    const user = await this.imUserEntity.findOne({
      userId: param.id,
      type: param.type,
    });
    await this.imSocketEvent.send(
      user.socketId,
      JSON.stringify({ action: 2, data: '修改成功' })
    );
  }
  @Event('putMessage')
  async putMessage(msg: any) {
    console.log('isOnline====111111111=>', msg);
    const user = await this.imUserService.findOne({ userId: msg.userId, type: 1 })
    if (user && user.socketId) {
      const isOnline = await this.imSocketEvent.online(user.socketId)
      console.log('isOnline=====>', isOnline);
      if (isOnline) {
        // 组装消息类容 
      // 1: 谁给你 点赞，评论，收藏 (用户的nickname)
      // 2：点赞内容 (博客id,博客内容)
      // 3：点击跳转链接
      let targetUser = await this.userInfoSrv.personal(msg.senderId)
      let message={
        userId:targetUser.id,
        sn:targetUser.sn,
        nickname:targetUser.nickname,
        headimgurl:targetUser.headimgurl,
        type:msg.type,
        action:msg.action,
        blogId:msg.targetId,
        commentId:msg.commentId
      }
         await this.imSocketEvent.sendMessage(user.socketId, message);
      }
    }
  }
}
